<template>
  <div class="monitor-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      :title="serverInfo?.name || '服务器监控'"
      fixed
      placeholder
      left-arrow
      @click-left="$router.back()"
      :border="false"
    >
      <template #right>
        <van-icon name="replay" size="20" @click="refreshData" />
      </template>
    </van-nav-bar>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="content-wrapper">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <van-loading type="spinner" size="36px">加载中...</van-loading>
        </div>

        <template v-else-if="monitorData">
          <!-- 服务器信息卡片 -->
          <div class="info-card">
            <div class="info-header">
              <van-icon name="desktop-o" size="24" color="#1989fa" />
              <h3>基本信息</h3>
            </div>
            <van-cell-group inset>
              <van-cell title="服务器名称" :value="serverInfo.name" />
              <van-cell title="主机地址" :value="`${serverInfo.host}:${serverInfo.port}`" />
              <van-cell title="用户名" :value="serverInfo.username" />
              <van-cell v-if="serverInfo.group_name" title="分组" :value="serverInfo.group_name" />
              <van-cell v-if="serverInfo.expire_date" title="到期时间" :value="formatExpireDate(serverInfo.expire_date)" />
            </van-cell-group>
          </div>

          <!-- CPU监控 -->
          <div class="monitor-card">
            <div class="card-header">
              <van-icon name="chart-trending-o" color="#1989fa" />
              <span>CPU使用率</span>
            </div>
            <div class="progress-wrapper">
              <van-circle
                v-model:current-rate="monitorData.cpu"
                :rate="monitorData.cpu"
                :speed="100"
                :text="`${monitorData.cpu}%`"
                :color="getColorByCpu(monitorData.cpu)"
                size="120px"
                layer-color="#f2f3f5"
              />
            </div>
            <van-cell-group inset>
              <van-cell title="核心数" :value="`${monitorData.cpuCores || '-'} 核`" />
            </van-cell-group>
          </div>

          <!-- 内存监控 -->
          <div class="monitor-card">
            <div class="card-header">
              <van-icon name="apps-o" color="#07c160" />
              <span>内存使用</span>
            </div>
            <div class="progress-wrapper">
              <van-circle
                v-model:current-rate="monitorData.memory"
                :rate="monitorData.memory"
                :speed="100"
                :text="`${monitorData.memory}%`"
                :color="getColorByMemory(monitorData.memory)"
                size="120px"
                layer-color="#f2f3f5"
              />
            </div>
            <van-cell-group inset>
              <van-cell title="已用内存" :value="monitorData.memoryUsed || '-'" />
              <van-cell title="总内存" :value="monitorData.memoryTotal || '-'" />
            </van-cell-group>
          </div>

          <!-- 磁盘监控 -->
          <div class="monitor-card">
            <div class="card-header">
              <van-icon name="records" color="#ff976a" />
              <span>磁盘使用</span>
            </div>
            <div class="progress-wrapper">
              <van-circle
                v-model:current-rate="monitorData.disk"
                :rate="monitorData.disk"
                :speed="100"
                :text="`${monitorData.disk}%`"
                :color="getColorByDisk(monitorData.disk)"
                size="120px"
                layer-color="#f2f3f5"
              />
            </div>
            <van-cell-group inset>
              <van-cell title="已用空间" :value="monitorData.diskUsed || '-'" />
              <van-cell title="总空间" :value="monitorData.diskTotal || '-'" />
            </van-cell-group>
          </div>

          <!-- 系统信息 -->
          <div class="monitor-card">
            <div class="card-header">
              <van-icon name="info-o" color="#9c27b0" />
              <span>系统信息</span>
            </div>
            <van-cell-group inset>
              <van-cell title="运行时间" :value="monitorData.uptime || '-'" />
              <van-cell title="在线用户" :value="monitorData.users || '-'" />
              <van-cell title="网络连接" :value="monitorData.connections || '-'" />
            </van-cell-group>
          </div>

          <!-- 更新时间 -->
          <div class="update-time">
            <van-icon name="clock-o" />
            <span>更新时间: {{ updateTime }}</span>
          </div>
        </template>

        <!-- 错误状态 -->
        <van-empty
          v-else
          description="获取监控数据失败"
          image="error"
        >
          <van-button type="primary" @click="loadMonitorData">
            重新加载
          </van-button>
        </van-empty>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRoute } from 'vue-router'
import { showToast } from 'vant'
import serverAPI from '@/api/servers'

const route = useRoute()

// 状态
const loading = ref(true)
const refreshing = ref(false)
const serverInfo = ref(null)
const monitorData = ref(null)
const updateTime = ref('')

// 定时器
let timer = null

// 获取服务器信息
const loadServerInfo = async () => {
  try {
    const response = await serverAPI.getById(route.params.serverId)
    serverInfo.value = response.server
  } catch (error) {
    console.error('❌ 获取服务器信息失败:', error)
    showToast('获取服务器信息失败')
  }
}

// 获取监控数据
const loadMonitorData = async () => {
  try {
    console.log('📱 获取监控数据')
    const data = await serverAPI.getMonitoring(route.params.serverId)
    monitorData.value = data
    updateTime.value = new Date().toLocaleTimeString()
    console.log('✅ 监控数据:', data)
  } catch (error) {
    console.error('❌ 获取监控数据失败:', error)
    showToast('获取监控数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  await loadMonitorData()
  showToast({ message: '刷新成功', position: 'top' })
}

// 下拉刷新
const onRefresh = async () => {
  await loadMonitorData()
  refreshing.value = false
}

// 格式化到期时间
const formatExpireDate = (dateStr) => {
  if (!dateStr) return ''
  
  const expireDate = new Date(dateStr)
  const now = new Date()
  const diff = expireDate.getTime() - now.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days < 0) return '已到期'
  if (days === 0) return '今天到期'
  if (days <= 7) return `${days}天后到期`
  
  return expireDate.toLocaleDateString()
}

// 根据CPU使用率获取颜色
const getColorByCpu = (value) => {
  if (value >= 90) return '#ee0a24'
  if (value >= 70) return '#ff976a'
  return '#1989fa'
}

// 根据内存使用率获取颜色
const getColorByMemory = (value) => {
  if (value >= 90) return '#ee0a24'
  if (value >= 80) return '#ff976a'
  return '#07c160'
}

// 根据磁盘使用率获取颜色
const getColorByDisk = (value) => {
  if (value >= 90) return '#ee0a24'
  if (value >= 80) return '#ff976a'
  return '#ff976a'
}

// 页面加载
onMounted(async () => {
  console.log('📱 监控页加载')
  await loadServerInfo()
  await loadMonitorData()
  
  // 每30秒自动刷新
  timer = setInterval(() => {
    loadMonitorData()
  }, 30000)
})

// 页面卸载
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.monitor-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

/* 内容区域 */
.content-wrapper {
  padding: 16px;
}

/* 加载容器 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 信息卡片 */
.info-card {
  margin-bottom: 16px;
}

.info-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: white;
  border-radius: 12px 12px 0 0;
}

.info-header h3 {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin: 0;
}

/* 监控卡片 */
.monitor-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 16px;
}

/* 进度圈容器 */
.progress-wrapper {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

/* 更新时间 */
.update-time {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin-top: 16px;
  color: #969799;
  font-size: 13px;
}

/* Vant样式覆盖 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: bold;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-nav-bar__arrow) {
  color: white !important;
}

:deep(.van-cell-group) {
  margin-top: 0;
}

:deep(.van-circle__text) {
  font-size: 20px;
  font-weight: bold;
}
</style>

